//
//  KLPhotoBrowserCell.swift
//  BCWeiBo
//
//  Created by bcmac3 on 16/4/5.
//  Copyright © 2016年 KellenYangs. All rights reserved.
//

import UIKit
import SDWebImage

protocol KLPhotoBrowserCellDelegate: NSObjectProtocol {
    
    /// 结束缩放
    func photoBrowserCellDidTapImage()
}

class KLPhotoBrowserCell: UICollectionViewCell {
    /// 照片代理
    weak var photoDelegate: KLPhotoBrowserCellDelegate?
    
    /// 图像的 URL
    var imageURL: NSURL? {
        didSet {
            // 显示菊花
            indicator.startAnimating()
            
            // 重设 scrollView
            resetScrollView()
            
            imageView.sd_setImageWithURL(imageURL!) { (image, _, _, _) -> Void in
                // 隐藏菊花
                self.indicator.stopAnimating()
                // 下载完成之后自动设置图片大小
                self.setupImagePostion()
            }
        }
    }
    
    /// 重设 ScrollView 的偏移属性
    private func resetScrollView() {
        // 重设 imageView 的形变
        imageView.transform = CGAffineTransformIdentity
        
        scrollView.contentInset = UIEdgeInsetsZero
        scrollView.contentOffset = CGPointZero
        scrollView.contentSize = CGSizeZero
    }
    
    private func setupImagePostion()
    {
        let s = self.displaySize(imageView.image!)
        // 图像高度比视图高度小，短图
        if s.height < scrollView.bounds.height {
            // 垂直居中
            let y = (scrollView.bounds.height - s.height) * 0.5
            imageView.frame = CGRect(origin: CGPointZero, size: s)
            // 设置间距，能够保证缩放完成后，同样能够显示完整画面
            scrollView.contentInset = UIEdgeInsets(top: y, left: 0, bottom: y, right: 0)
        } else {
            // 长图
            imageView.frame = CGRect(origin: CGPointZero, size: s)
            // contentSize
            scrollView.contentSize = s
        }
    }
    /// 计算显示的图像尺寸，以 scrollView 的宽度为基准
    private func displaySize(image: UIImage) -> CGSize
    {
        // 图像宽高比
        let scale = image.size.height / image.size.width
        let height = scale * scrollView.bounds.width
        return CGSize(width: scrollView.bounds.width, height: height)
    }
    
    // MARK: - 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        // 1.初始化UI
        setupUI()
    }
    
    private func setupUI(){
        // 1. 添加控件
        contentView.addSubview(scrollView)
        scrollView.addSubview(imageView)
        contentView.addSubview(indicator)
        
        // 2. 控件布局
        scrollView.frame = UIScreen.mainScreen().bounds
        indicator.center = scrollView.center
        
        // 3.设置imageView手势监听
        let tap = UITapGestureRecognizer(target: self, action: "clickImage")
        imageView.addGestureRecognizer(tap)
        imageView.userInteractionEnabled = true
    }
    
    func clickImage()
    {
        photoDelegate?.photoBrowserCellDidTapImage()
    }
    
    // MARK: 懒加载控件
    private lazy var scrollView: UIScrollView = {
        let sc = UIScrollView()
        sc.delegate = self
        
        // 最大/小缩放比例
        sc.minimumZoomScale = 0.5
        sc.maximumZoomScale = 2.0
        return sc
    }()
    lazy var imageView = UIImageView()
    /// 大菊花
    private lazy var indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension KLPhotoBrowserCell: UIScrollViewDelegate
{
    /// 告诉 scrollView 要缩放的控件
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imageView
    }
    /// 在缩放完成后，会被调用一次
    ///
    /// :param: scrollView scrollView
    /// :param: view       被缩放的 view
    /// :param: scale      缩放完成后的缩放比例
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        
        // 重新计算间距
        // 通过 transform 改变view的缩放，bound本身没有变化，frame会变化
        var offsetX = (scrollView.bounds.width - view!.frame.width) * 0.5
        // 如果边距小于0，需要修正
        offsetX = offsetX < 0 ? 0 : offsetX
        
        var offsetY = (scrollView.bounds.height - view!.frame.height) * 0.5
        offsetY = offsetY < 0 ? 0 : offsetY
        
        scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: 0, right: 0)
    }

}
